package org.webframe.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.webframe.entity.SysPermission;
import org.webframe.entity.SysUser;
import org.webframe.service.SysPermissionService;
import org.webframe.service.SysUserService;

@Service
public class MyUserDetailsService implements UserDetailsService{
	
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService sysPermissionService;

	public UserDetails loadUserByUsername(String loginname) throws UsernameNotFoundException {
		SysUser example = new SysUser();
    	example.setLoginname(loginname);
        SysUser sysUser = sysUserService.findByExample(example);
        if(sysUser == null){
            throw new UsernameNotFoundException(loginname);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        List<SysPermission> sysPermissionList = sysPermissionService.findByLoginname(loginname);
        for (SysPermission sysPermission : sysPermissionList) {
        	authorities.add(new SimpleGrantedAuthority(sysPermission.getCode()));
		}
        sysUser.setAuthorities(authorities);
        return sysUser;
	}

}
